package com.gzw.scm.activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.gzw.scm.DEL.DBManager;
import com.gzw.scm.MyApplication;
import com.gzw.scm.R;
import com.gzw.scm.adapter.ZZXFPAdapter;
import com.gzw.scm.base.BaseActivity;
import com.gzw.scm.bean.Constant;
import com.gzw.scm.bean.DispatchResult;
import com.gzw.scm.utils.HttpUtils;
import com.gzw.scm.utils.T;
import com.gzw.scm.utils.UrlUtils;
import com.gzw.scm.view.SwipeRefreshLayout;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Administrator on 2017/4/24.
 */

public class FPZZXActivity extends BaseActivity{
    private Context mContext;
    private RecyclerView mRecyclerView;
    private Toolbar toolbar;
    private Intent intent;
    private Button btn_sure,btn_delete;
    private TextView tv_seleteAll;
    private boolean isCheck = false;
    private DBManager dbManager;
    private List<String> ls_bh,ls_xzbh;
    private ZZXFPAdapter zzxfpAdapter;
    private ProgressDialog mProgressDialog;
    private SwipeRefreshLayout mSwipeLayout;
    private String did;
    private String dataType = "ZBfp";
    private Logger log;

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_fpzzx);
    }

    @Override
    protected void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_fp);
        btn_sure = (Button)findViewById(R.id.btn_sure);
        btn_delete = (Button)findViewById(R.id.btn_delete);
        tv_seleteAll = (TextView) findViewById(R.id.ic_head1).findViewById(R.id.tv_selectAll);
        //初始化 log
        log=Logger.getLogger(this.getClass());
    }

    @Override
    protected void initData() {
        mContext = this;
        toolbar.setTitle("周转箱分配");
        setSupportActionBar(toolbar);

        intent = getIntent();
        did=intent.getStringExtra("did");

        /**
        * 刷新框架
        * */
        mRecyclerView.setHasFixedSize(true);
        //设置布局管理器
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        //设置Item增加、移除动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //添加默认分割线
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);

        mSwipeLayout.setColor(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        mSwipeLayout.setMode(SwipeRefreshLayout.Mode.DISABLED);
        mSwipeLayout.setLoadNoFull(false);

        dbManager=new DBManager(mContext);
        ls_bh= new ArrayList<>();
        ls_xzbh = new ArrayList<>();

        setData();
    }

    @Override
    protected void initEvents() {
        toolbar.setNavigationOnClickListener(new myOnClick());
        btn_sure.setOnClickListener(new myOnClick());
        btn_delete.setOnClickListener(new myOnClick());
        tv_seleteAll.setOnClickListener(new myOnClick());
    }

    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.btn_sure:
                    senddata();
                    break;
                case R.id.btn_delete:
                    deleteZzxbh();
                    break;
                case R.id.tv_selectAll:
                    if (ls_bh != null) {
                        if (isCheck == false) {
                            // 遍历list的长度，将MyAdapter中的map值全部设为true
                            for (int i = 0; i < ls_bh.size(); i++) {
                                ZZXFPAdapter.getIsSelected().put(i, true);
                            }
                            zzxfpAdapter.notifyDataSetChanged();
                            //改变状态
                            isCheck = true;
                        } else {
                            // 遍历list的长度，将已选的按钮设为未选
                            for (int i = 0; i < ls_bh.size(); i++) {
                                if (ZZXFPAdapter.getIsSelected().get(i)) {
                                    ZZXFPAdapter.getIsSelected().put(i, false);
                                }
                            }
                            zzxfpAdapter.notifyDataSetChanged();
                            isCheck = false;
                        }
                    }
                    break;
                default:
                    finish();
                    break;
            }
        }
    }

    /**
     * 扫描结果
     * */
    @Override
    protected String scanRelust(String code){
        if(code.contains("该二维码不是周转箱")){
            T.showShort(mContext,"该二维码不是周转箱");
        }else {
            isScan(code);
        }
        return code;
   };

    /**
    * 判断是否已扫
    * */
    private void isScan(String bh){
     Boolean isExist = dbManager.IsExistZzxbh(bh,dataType,MyApplication.getUserInfo().getDid());
        if(isExist){
            T.showShort(mContext,"该二维码已扫描");
        }else{
            dbManager.addZzxbh(bh,dataType,MyApplication.getUserInfo().getDid());
            setData();
        }
    }

    /**
     * 列表赋值
     * */
    private void setData(){
        ls_bh.clear();
        List<String> lsbh=dbManager.selectFPZzxbh(dataType,MyApplication.getUserInfo().getDid());
        if(lsbh==null){
            return;
        }else {
        ls_bh.addAll(lsbh);
        }
        if(ls_bh==null){
            return;
        }

        zzxfpAdapter = new ZZXFPAdapter(ls_bh);
        mRecyclerView.setAdapter(zzxfpAdapter);

        zzxfpAdapter.setOnRecyclerViewListener(new ZZXFPAdapter.OnRecyclerViewListener() {
            @Override
            public void onItemClick(int position) {
               if(ZZXFPAdapter.getIsSelected().get(position)==true){
                   ZZXFPAdapter.getIsSelected().put(position, false);
                   zzxfpAdapter.notifyDataSetChanged();
               }else{
                   ZZXFPAdapter.getIsSelected().put(position, true);
                   zzxfpAdapter.notifyDataSetChanged();
               }
            }

            @Override
            public boolean onItemLongClick(int position) {
                return false;
            }
        });

    }

    /**
     * 删除周转箱编号
     * */
    private void deleteZzxbh(){
        List<String> lsbh=new ArrayList<>();
        for (int i = 0; i < ls_bh.size(); i++) {
            if (zzxfpAdapter.getIsSelected().get(i)) {
                lsbh.add(ls_bh.get(i));
            }
        }
        if(lsbh.size()==0){
            T.showShort(mContext,"请先选择要删除的编号!");
        }else {
            showDeleteInfo(lsbh);
        }
    }

    /**
     * 删除数据是的提示框
     * */
    private void showDeleteInfo(final List<String> ls_bh){
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("确定要删除这"+ls_bh.size()+"个编号吗?");
        builder.setPositiveButton("确定", (dialog, which) ->  {
                dbManager.deleteFPZzxbh(ls_bh,dataType,MyApplication.getUserInfo().getDid());
                setData();
        });
        builder.setNegativeButton("取消", (dialog, which) -> {
        });
        builder.show();
    }

    /**
     * 上传数据
     * */
    private void senddata(){
        List<String> lsbh=new ArrayList<>();
        for (int i = 0; i < ls_bh.size(); i++) {
            if (zzxfpAdapter.getIsSelected().get(i)) {
                lsbh.add(ls_bh.get(i));
            }
        }
        if(lsbh.size()==0){
            T.showShort(mContext,"请先选择要分配的编号!");
        }else {
            showSendInfo(lsbh);
        }
    }

    /**
     * 删除数据是的提示框
     * */
    private void showSendInfo(final List<String> ls_bh){
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("确定要分配这"+ls_bh.size()+"个周转箱吗?");
        builder.setPositiveButton("确定", (dialog, which) -> {
                ls_xzbh.clear();
                ls_xzbh.addAll(ls_bh);
                String idStr=new String();
                for (String str:ls_bh){
                    idStr=idStr+str+",";
                }
                idStr = idStr.substring(0, (idStr.length()-1));

                SendTask sendTask = new SendTask();
                sendTask.execute(idStr);

        });
        builder.setNegativeButton("取消", (dialog, which) -> {
        });
        builder.show();
    }

    /**
     * 上传的数据请求
     * */

    public class SendTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(String... params) {
            SharedPreferences sharedPreferences = getSharedPreferences(Constant.USERINFO_KEY, Context.MODE_PRIVATE);
            int sdid = sharedPreferences.getInt(Constant.DID_KEY, 0);
            String json="tboxno="+params[0]+"&sdid="+sdid+"&did="+ did +"&belongid="+String.valueOf(MyApplication.getUserInfo().getBelongId());
            String url =json.replace("\\","");
            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("tboxhq.do","disTbox"),url);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();

            try {

                if (result == null || result.length() == 0) {
                showAlertDialog("连接异常");
                return;
            }
            DispatchResult dispatchResult = new Gson().fromJson(result, DispatchResult.class);
            if(dispatchResult.getOkMsg().equals("周转箱分配成功")){
                showAlertDialog("周转箱分配成功");
                dbManager.deleteFPZzxbh(ls_xzbh,dataType,MyApplication.getUserInfo().getDid());
                setData();
            }else if(dispatchResult.getOkMsg().equals("部分周转箱分配失败")){

                showAlertDialog(String.valueOf(dispatchResult.getTbox())+"分配失败");
                List<String> ls = dispatchResult.getTbox();
                ls_xzbh.removeAll(ls);
                dbManager.deleteFPZzxbh(ls_xzbh,dataType,MyApplication.getUserInfo().getDid());
                setData();

            }else if(dispatchResult.getErrorMsg().equals("系统异常")){
                showAlertDialog("网络异常");
            }
            }catch (Exception e) {
                log.info("disTbox:"+e.toString()+"/result="+result);
                e.printStackTrace();
                showAlertDialog(e.toString());
            }
        }
    }


}
